<template>
  <div class="news-list-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">新闻列表</h1>
      <p class="page-subtitle">浏览和管理所有新闻文章</p>
    </div>
    
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card" shadow="hover">
      <div class="filter-content">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索新闻标题或内容"
          prefix-icon="i-ep-search"
          class="search-input"
          clearable
        />
        <el-select
          v-model="authorFilter"
          placeholder="选择作者"
          class="author-select"
          clearable
        >
          <el-option label="全部作者" value="" />
          <el-option
            v-for="author in authors"
            :key="author"
            :label="author"
            :value="author"
          />
        </el-select>
        <el-button type="primary" @click="handleSearch" icon="i-ep-search">
          搜索
        </el-button>
      </div>
    </el-card>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-spinner type="primary" />
      <p>正在加载新闻数据...</p>
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <el-alert
        title="加载失败"
        description="获取新闻数据时发生错误，请稍后重试。"
        type="error"
        show-icon
      />
      <el-button type="primary" @click="fetchNewsList">重试</el-button>
    </div>
    
    <!-- 空状态 -->
    <div v-else-if="newsList.length === 0" class="empty-container">
      <el-empty description="暂无新闻数据" />
    </div>
    
    <!-- 新闻列表 -->
    <div v-else class="news-grid">
      <div 
        v-for="(news, index) in newsList" 
        :key="news.id" 
        class="news-card"
        @click="goToDetail(news.id)"
        :style="{ animationDelay: `${index * 0.05}s` }"
      >
        <div class="news-header">
          <h3 class="news-title">{{ news.title }}</h3>
        </div>
        <div class="news-content">
          <p class="news-summary">{{ news.summary || news.content.substring(0, 100) }}...</p>
        </div>
        <div class="news-footer">
          <span class="news-author">{{ news.author }}</span>
          <span class="news-time">{{ formatDate(news.created_at) }}</span>
        </div>
      </div>
    </div>
    
    <!-- 分页 -->
      <el-pagination
      v-if="!loading && !error && newsList.length > 0"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getNewsList } from '../api/newsAPI.js'
const router = useRouter()

// 状态管理
const newsList = ref([])
const loading = ref(false)
const error = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')
const authorFilter = ref('')

// 计算所有作者列表
const authors = computed(() => {
  const authorSet = new Set(newsList.value.map(news => news.author))
  return Array.from(authorSet)
})

// 格式化日期 - 添加错误处理和更健壮的日期解析
const formatDate = (dateString) => {
  // 检查输入是否有效
  if (!dateString || dateString === 'null' || dateString === 'undefined') {
    return '未知时间'
  }
  
  try {
    // 尝试解析日期，处理不同格式的日期字符串
    const date = new Date(dateString)
    
    // 检查是否是有效日期
    if (isNaN(date.getTime())) {
      return '无效时间'
    }
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch (error) {
    console.error('日期格式化错误:', error)
    return '时间格式错误'
  }
}

// 获取新闻列表
const fetchNewsList = async () => {
  loading.value = true
  error.value = ''
  try {
    const response = await getNewsList({
      page: currentPage.value,
      pageSize: pageSize.value
    })
    newsList.value = response.data || []
    total.value = response.total || 0
  } catch (err) {
    console.error('获取新闻列表失败:', err)
    error.value = err.message || '获取新闻列表失败'
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchNewsList() // 可以根据实际API支持情况调整搜索逻辑
}

// 跳转到新闻详情
const goToDetail = (newsId) => {
  router.push(`/news/${newsId}`)
}

// 分页处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  fetchNewsList()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchNewsList()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchNewsList()
})
</script>

<style scoped>
.news-list-container {
  max-width: 1200px;
  margin: 0 auto;
  animation: pageLoad 0.6s ease-out;
}

@keyframes pageLoad {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 页面标题区域 */
.page-header {
  text-align: center;
  padding: var(--spacing-xl) 0;
  margin-bottom: var(--spacing-xl);
  border-bottom: 1px solid var(--border-color);
}

.page-title {
  font-size: var(--font-size-xl);
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 var(--spacing-xs);
  letter-spacing: -0.5px;
}

.page-subtitle {
  font-size: var(--font-size-base);
  color: var(--text-secondary);
  margin: 0;
  font-weight: 400;
}

/* 筛选卡片 */
.filter-card {
  margin-bottom: var(--spacing-xl);
  border-radius: var(--border-radius-base);
  border: none;
  box-shadow: var(--box-shadow-light);
  transition: var(--transition-base);
}

.filter-card:hover {
  box-shadow: var(--box-shadow-medium);
}

.filter-content {
  display: flex;
  gap: var(--spacing-md);
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  min-width: 200px;
}

.author-select {
  width: 180px;
}

/* 状态容器 */
.loading-container,
.error-container,
.empty-container {
  min-height: 400px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: var(--spacing-md);
  text-align: center;
}

.error-container {
  gap: var(--spacing-lg);
}

/* 新闻网格 */
.news-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: var(--spacing-lg);
  margin-bottom: var(--spacing-xl);
}

/* 新闻卡片 */
.news-card {
  background: white;
  border-radius: var(--border-radius-base);
  padding: var(--spacing-lg);
  box-shadow: var(--box-shadow-light);
  transition: var(--transition-base);
  cursor: pointer;
  display: flex;
  flex-direction: column;
  height: 100%;
  animation: cardSlideIn 0.5s ease-out forwards;
  opacity: 0;
  transform: translateY(20px);
}

@keyframes cardSlideIn {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.news-card:hover {
  box-shadow: var(--box-shadow-medium);
  transform: translateY(-6px);
}

.news-header {
  margin-bottom: var(--spacing-base);
}

.news-title {
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  transition: var(--transition-base);
}

.news-card:hover .news-title {
  color: var(--primary-color);
}

.news-content {
  flex: 1;
  margin-bottom: var(--spacing-base);
}

.news-summary {
  color: var(--text-regular);
  line-height: 1.7;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 4;
  -webkit-box-orient: vertical;
}

.news-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
}

.news-author {
  background-color: var(--primary-color);
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: var(--font-size-xs);
}

/* 分页 */
.pagination {
  margin-top: var(--spacing-xl);
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .author-select {
    width: 100%;
  }
  
  .news-grid {
    grid-template-columns: 1fr;
    gap: var(--spacing-md);
  }
  
  .news-card {
    padding: var(--spacing-base);
  }
  
  .page-title {
    font-size: var(--font-size-lg);
  }
  
  .news-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-xs);
  }
}

/* 确保分页文本全中文显示 - 使用更精确的样式覆盖 */
:deep(.el-pagination__total) {
  font-size: 14px;
  color: #606266;
}

/* 自定义页码跳转框 */
:deep(.el-pagination__jump) {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 完全覆盖"Go to"文本 */
:deep(.el-pagination__jump-label) {
  font-size: 0 !important; /* 强制隐藏原始文本 */
  position: relative;
}

:deep(.el-pagination__jump-label::after) {
  content: "前往";
  font-size: 14px;
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
}

/* 处理页码输入框 */
:deep(.el-pagination__editor) {
  margin: 0 5px;
}

/* 在页码输入框后添加"页"文本 */
:deep(.el-pagination__jump)::after {
  content: "页";
  font-size: 14px;
  color: #606266;
}

/* 确保每页显示数量选择器的文本正确 */
:deep(.el-pagination__sizes) {
  display: flex;
  align-items: center;
}

:deep(.el-pagination__sizes .el-select) {
  margin: 0 5px;
}

@media (max-width: 768px) {
  .news-grid {
    grid-template-columns: 1fr;
  }
  
  h2 {
    font-size: 1.5rem;
  }
}
</style>